package me.zhanshi123.pixelpaygui.gui.open

import io.izzel.taboolib.util.item.ItemBuilder
import io.izzel.taboolib.util.lite.Materials
import me.zhanshi123.kit.Kit
import org.bukkit.Bukkit
import org.bukkit.inventory.Inventory

object OpenGui {
    fun getInventory(page: Int = 1): Inventory {
        val holder = OpenGuiHolder()
        val inventory = Bukkit.createInventory(holder, 54, "礼包购买")
        holder.page = page
        setInventory(inventory, page)
        return inventory
    }

    val next = ItemBuilder(Materials.ARROW.parseItem()).name("§a下一页").build()
    val previous = ItemBuilder(Materials.ARROW.parseItem()).name("§a上一页").build()
    val nextSlot = 51
    val previousSlot = 47

    val kitSlots = arrayOf(10, 11, 12, 13, 14, 15, 16, 19, 20, 21, 22, 23, 24, 25, 28, 29, 30, 31, 32, 33, 34)

    fun setInventory(inventory: Inventory, page: Int) {
        inventory.clear()
        if (page != 1) {
            inventory.setItem(previousSlot, previous)
        }
        val holder = inventory.holder as OpenGuiHolder
        holder.page = page
        inventory.setItem(nextSlot, next)
        for (i in (page - 1) * kitSlots.size..page * kitSlots.size) {
            val entry = getKits().entries.toList().getOrNull(i) ?: continue
            inventory.setItem(kitSlots[i % kitSlots.size], ItemBuilder(Materials.PAPER.parseItem())
                    .name("§a${entry.value.name}")
                    .lore("",
                            "§f价格: §a${entry.value.money}",
                            "",
                            "§c点击购买")
                    .build()
            )
        }
    }

    fun getKits(): Map<String, Kit> {
        Class.forName("cn.i8mc.vexrmb.Main")
        val kits = cn.i8mc.vexrmb.Main.getInstance().kitManager
        val field = kits.javaClass.getDeclaredField("data")
        field.isAccessible = true
        return field.get(kits) as Map<String, Kit>
    }
}